import Vue from 'vue';
import overlayComponent from './overlay.vue';
let modalStack = [];
let _zIndex = 9000;  //toast  90001   confirm:10000
let overlay;
const overlayManager = {
    lockCount: 0,
    get topStack() {
        return modalStack[modalStack.length - 1];
    },
    getZIndex() {
        return ++_zIndex;
    },
    openOverlay(vm, config) {
        let { zIndex, duration, overlayClass, overlayStyle, id } = config;
        modalStack.push({
            vm,
            config: {
                id,
                zIndex,
                duration,
                overlayClass,
                overlayStyle,
            }
        });
        overlayManager.updateOverlay();

    },
    updateOverlay() {
        const { clickHandle, topStack } = overlayManager;
        if (!overlay) {
            overlay = mount(overlayComponent, {
                nativeOn: {
                    click: clickHandle,
                },
            });
        }
        if (topStack) {
            const { vm, config } = topStack;
            const el = vm.$el;
            if (vm.getContainer && vm.getContainer.toLowerCase() == 'body') {
                document.body.appendChild(overlay.$el);
            } else {
                el && el.parentNode && el.parentNode.nodeType !== 11 ? el.parentNode.appendChild(overlay.$el) : document.body.appendChild(overlay.$el);
            }
            Object.assign(overlay, config, {
                value: true,
            });
        } else {
            overlay.value = false;
        }
    },
    clickHandle() {
        const { topStack } = overlayManager;
        if (modalStack.length && topStack.vm.closeOnClickOverlay) {
            topStack.vm.$emit('click-overlay');
            topStack.vm.close();
        }
    },
    closeOverlay(vm) {
        if (modalStack.length) {
            if (overlayManager.topStack.vm === vm) {
                modalStack.pop(); //删除最后一个
                overlayManager.updateOverlay();
            } else {
                modalStack = modalStack.filter((item) => item.vm !== vm);
            }
        }
    }
}


function mount(Component, data) {
    const instance = new Vue({
        props: Component.props,
        render(h) {
            return h(Component, {
                props: this.$props,  //this指向 Component
                ...data,
            })
        }
    }).$mount();
    return instance;
}
export default overlayManager;